import { generate } from '@/api/live/live';
import { ScriptType } from '@/enum/enums';
import { EventBus } from '@/event-bus.js';
export const userEnterMatch = {
  data() {
    return {
      matchUserEnterInterval: null,
      matchTime: 20000,
    };
  },
  created() {
    // for (let index = 0; index < 3; index++) {
    //   this.userEnterDataList.push({
    //     nickName: "user" + index,
    //     content: '进入直播间',
    //     hasGen: false,
    //     timestamp: Date.now()
    //   });
    // }
    // this.matchUserEnterInterval = setInterval(() => {
    //   this.findNewUserEnter();
    // }, 2000);

    EventBus.$on("userEnterMatchSendWebSocket", (type) => {
      if (this.userEnterSetting.open) {
        this.findNewUserEnter();
      }
    });
  },
  beforeDestroy() {
    EventBus.$off('userEnterMatchSendWebSocket');
  },
  destroy() { },
  mounted() { },
  computed: {
    pageConfig() {
      return this.$store.state.page.config;
    },
    userEnterSetting() {
      return this.pageConfig.userEnterSetting;
    },
    userEnterContentList() {
      let list = [];
      const content = this.$store.state.page.userEnterContent;
      if (!content) {
        return list;
      }
      return content.split('\n').filter(line => line.trim() !== '');
    }
  },
  methods: {
    findNewUserEnter() {
      const now = Date.now();
      const timeThreshold = now - 50000;
      // 筛选出过去50秒内的新用户
      const newUsers = this.userEnterDataList.filter(user => user.timestamp >= timeThreshold && !user.hasGen).sort((a, b) => b.timestamp - a.timestamp);
      if (newUsers.length === 0) return;

      // 动态计算实际需要处理的数量
      const maxUsersToProcess = Math.min(
        this.userEnterSetting.userCount,
        newUsers.length
      );
      // 获取需要处理的最新用户（已按时间倒序排列，取前N个）
      const targetUsers = newUsers.slice(0, maxUsersToProcess);

      const text = this.userEnterContentList[Math.floor(Math.random() * this.userEnterContentList.length)];
      let nickName = '';
      targetUsers.forEach(user => {
        let tempName = user.nickName;
        if (this.pageConfig.nameSize != '') {
          tempName = tempName.substring(0, this.pageConfig.nameSize);
        }
        if (nickName.includes(tempName)) {
          return;
        }
        nickName += tempName + "";
        //匹配到关键字 就要将这个人去除掉
        user.hasGen = true;
      });
      generate({
        userName: nickName,
        text: text,
        scriptType: ScriptType.USER_ENTER.code,
      });
    }
  }
}
